package com.shareppy.norman.sqlite.schema;

import java.lang.reflect.Field;
import java.util.List;

import com.shareppy.norman.core.annotations.Inherited;
import com.shareppy.norman.core.annotations.NotNull;
import com.shareppy.norman.core.annotations.Unique;
import com.shareppy.norman.core.entity.AbstractEntity;
import com.shareppy.norman.core.schema.SchemaGenerator;
import com.shareppy.norman.core.util.EntityUtils;
import com.shareppy.utils.ReflectionUtils;

public class SQLiteSchemaGenerator implements SchemaGenerator{

	@Override
	public <T extends AbstractEntity> String ddl(Class<T> entityClass) throws Exception {
		StringBuilder ddl = new StringBuilder("CREATE TABLE ");
		ddl.append(EntityUtils.getTableName(entityClass)).append("(");
		List<String> columns = EntityUtils.getColumns(entityClass);
		StringBuilder columnsddl = new StringBuilder(AbstractEntity.ID_COLUMN);
		columnsddl.append(" INTEGER PRIMARY KEY AUTOINCREMENT");
		for (String column : columns) {
			if (AbstractEntity.ID_COLUMN.equals(column)) {
				continue;
			}
			Field field = ReflectionUtils.getAccessibleField(entityClass, column, Inherited.class);
			columnsddl.append(",").append(column).append(" ")
					.append(EntityUtils.getDBtype(field));
			NotNull notNull = field.getAnnotation(NotNull.class);
			if (notNull != null) {
				columnsddl.append(" NOT NULL");
				if( notNull.unique() ){
					columnsddl.append(" UNIQUE");
				}
			}
			Unique unique = field.getAnnotation(Unique.class);
			if (unique != null) {
				columnsddl.append(" UNIQUE");
			}
		}
		ddl.append(columnsddl.toString()).append(")");
		return ddl.toString();
	}
	
}
